/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is ThumbsDown.
 *
 * The Initial Developer of the Original Code is Atte Kemppilä.
 * Portions created by the Initial Developer are Copyright (C) 2011
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */


const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;

Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");

Cu.import("resource://thumbsdown/ScriptStore.jsm");
Cu.import("resource://thumbsdown/ThumbsDown.jsm");
Cu.import("resource://thumbsdown/util.jsm");


const manager =
{
    STRING_BUNDLE_URL: "chrome://thumbsdown/locale/manager.properties",
    
    onLoad: function()
    {
        let self = this;
        
        this._ = getStringBundleGetter(Services.strings.createBundle(this.STRING_BUNDLE_URL));
        
        let toolbarMode = document.getElementById("toolbar").getAttribute("mode");
        document.getElementById("mitem_use_" + toolbarMode).setAttribute("checked", true);
        
        this.disabledFilter = document.getElementById("tbutton_filter");
        this.nameFilter = document.getElementById("tbox_filter");
        
        let thumbnailTypeNames = {};
        for each (let type in ["image-map", "img", "css-background-image"])
            thumbnailTypeNames[type] = this._("thumbnailType." + type);
        
        let scriptTypeNames = {};
        for each (let type in ["direct", "regexp", "custom", "wrapped"])
            scriptTypeNames[type] = this._("type." + type);
        
        this.tree = document.getElementById("tree");
        this.tree.view = this.treeView = new ScriptTreeView([], thumbnailTypeNames, scriptTypeNames);
        
        let controller = new Controller(this.treeView);
        controller._ = this._;
        controller.disabled = true;
        window.controllers.insertControllerAt(0, controller);
        window.updateCommands("tree-select");
        
        callLater(0, this, function()
        {
            ScriptStore.open();
            this.treeView.model = ScriptStore.getScripts(true).slice();
            this.treeView.filter = this._getFilter();
            
            // refresh lastUsed and counter columns every 3 seconds
            let refreshDelay = 3 * 1000;
            let refreshColumns = [this.tree.columns.getNamedColumn(id) for each (id in ["tcol_lastUsed", "tcol_counter"])];
            let refreshTree = function() { refreshColumns.forEach(function(col) { self.treeView.treeBoxObject.invalidateColumn(col); }); }
            this._treeRefreshTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
            this._treeRefreshTimer.initWithCallback({notify: refreshTree}, refreshDelay, Ci.nsITimer.TYPE_REPEATING_SLACK);
            
            Services.obs.addObserver(this, ScriptStore.TOPIC, false);
            
            controller.disabled = false;
            window.updateCommands("tree-select");
        });
    },
    
    onUnload: function()
    {
        Services.obs.removeObserver(this, ScriptStore.TOPIC);
        this._treeRefreshTimer.cancel();
    },
    
    onToolboxContextCommand: function(e)
    {
        document.getElementById("toolbar").setAttribute("mode", e.target.getAttribute("value"));
    },
    
    onTreeSelect: function()
    {
        window.updateCommands("tree-select");
    },
    
    onTreeDoubleClick: function(e)
    {
        if (e.button != 0)
            return;
        
        let row = {}, col = {};
        this.tree.treeBoxObject.getCellAt(e.clientX, e.clientY, row, col, {});
        if ((row.value == -1) || (col.editable))
             return;
        
        goDoCommand("cmd_editScript");
    },
    
    onFilterCommand: function()
    {
        this.treeView.filter = this._getFilter();
    },
    
    // nsIObserver
    observe: function(subject, topic, data)
    {
        switch (topic)
        {
            case ScriptStore.TOPIC:
                return this._observeScriptStore(subject, topic, data);
        }
    },
    
    _observeScriptStore: function(subject, topic, data)
    {
        callLater(0, this, function()
        {
            // When store is modified, just reset the model,
            // because even script edit can lead to rowCount changes in the tree due to filtering.
            this.treeView.model = ScriptStore.getScripts(true).slice();
        });
    },
    
    _getFilter: function()
    {
        let filters = [];
        
        if (this.disabledFilter.checked)
            filters.push(function(script) { return (! script.disabled); }); 
            
        let text = this.nameFilter.value.trim().toLocaleLowerCase();
        if (text.length > 0)
            filters.push(function(script) { return (script.nameLower.indexOf(text) != -1); });
        
        switch (filters.length)
        {
            case 0: return null;
            case 1: return filters[0];
            default: return filters.reduceRight(function(a, b) { return function(s) { return (b(s) && a(s)); }; });
        }
    },
};


function ScriptTreeView(scripts, thumbnailTypeNames, typeNames)
{
    this._model = scripts;
    this._thumbnailTypeNames = thumbnailTypeNames;
    this._typeNames = typeNames;
    
    this._view = this._model.slice();
    this._filter = null;
    this._sortColumn = null;
}

ScriptTreeView.prototype =
{
    QueryInterface: XPCOMUtils.generateQI([Ci.nsITreeView]),
    
    get view() { return this._view; },
    
    get model() { return this._model; },
    
    set model(model)
    {
        if (model == this._model)
            return;
        
        this._update(model, this._filter);
    },
    
    get filter() { return this._filter; },
    
    set filter(filter)
    {
        if (filter == this._filter)
            return;
        
        this._update(this._model, filter);
    },
    
    get selectedIndexes()
    {
        return [index for each (index in SelectionIterator(this.selection))];
    },
    
    get selectedIndex()
    {
        // selection.currentIndex is the currently focused index, but it's not neccessarily selected
        return ((this.selection.count == 1) ? SelectionIterator(this.selection).next() : -1);
    },
    
    _update: function(model, filter)
    {
        let selected;
        
        if (this.treeBoxObject)
        {
            // back-up selection
            let view = this._view;
            selected = [view[index].id for each (index in this.selectedIndexes)];
            
            this.selection.selectEventsSuppressed = true;
            this.treeBoxObject.beginUpdateBatch();
            this.treeBoxObject.rowCountChanged(0, -this.rowCount);
        }
        
        this._model = model;
        this._filter = filter;
        this._doFilter();
        this._doSort();
        
        if (this.treeBoxObject)
        {
            let selection = this.selection;
            let view = this._view;
            
            // restore selection
            for (let index = 0; index < view.length; index++)
                if (selected.indexOf(view[index].id) != -1)
                    selection.rangedSelect(index, index, true);
            
            this.treeBoxObject.endUpdateBatch();
            this.selection.selectEventsSuppressed = false;
        }
    },
    
    _doFilter: function()
    {
        if (this._filter)
        {
            let filter = this._filter;
            let model = this._model;
            let modelLength = model.length;
            let view = new Array(modelLength);
            let viewLength = 0;
            
            for (let i = 0; i < modelLength; i++)
                if (filter(model[i]))
                    view[viewLength++] = model[i];
            
            view.length = viewLength;
            this._view = view;
        }
        else
        {
            this._view = this._model.slice();
        }
    },
    
    _doSort: function(compare)
    {
        if (! this._sortColumn)
            return;
        
        if (! compare)
            compare = this._getCompare(this._sortColumn);
        if (! compare)
            return;
        
        if (this._sortColumn.element.getAttribute("sortDirection") == "descending")
        {
            let _compare = compare;
            compare = function(a, b) { return -_compare(a, b); }
        }
        
        this._view.sort(compare);
    },
    
    _getCompare: function(col)
    {
        let self = this;
        
        switch (col.id)
        {
            case "tcol_enabled": return function(a, b) { return a.disabled - b.disabled; };
            case "tcol_name": return function(a, b) { return a.nameLower.localeCompare(b.nameLower); };
            case "tcol_thumbnailType": return function(a, b) { return self._thumbnailTypeNames[a.thumbnailType].localeCompare(self._thumbnailTypeNames[b.thumbnailType]); };
            case "tcol_type": return function(a, b) { return self._typeNames[a.type].localeCompare(self._typeNames[b.type]); };
            case "tcol_created":  return function(a, b) { return (a.created ? a.created.getTime() : 0) - (b.created ? b.created.getTime() : 0); };
            case "tcol_modified": return function(a, b) { return (a.modified ? a.modified.getTime() : 0) - (b.modified ? b.modified.getTime() : 0); };
            case "tcol_lastUsed": return function(a, b) { return (a.lastUsed ? a.lastUsed.getTime() : 0) - (b.lastUsed ? b.lastUsed.getTime() : 0); };
            case "tcol_counter":  return function(a, b) { return a.counter - b.counter; };
            default: return null;
        }
    },
    
    // nsITreeView
    
    get rowCount() { return this._view.length; },
    
    cycleHeader: function(col)
    {
        let compare = this._getCompare(col);
        if (! compare)
            return;
        
        let sortDirection = ((col.element.getAttribute("sortDirection") == "ascending") ? "descending" : "ascending");
        
        // reset old sort column's sortDirection
        // note that removing attribute won't work because attribute won't get removed from persist store
        if (this._sortColumn)
            this._sortColumn.element.setAttribute("sortDirection", "natural");
        
        col.element.setAttribute("sortDirection", sortDirection);
        
        this._sortColumn = col;
        this._doSort(compare);
        this.treeBoxObject.invalidate();
    },
    
    getCellProperties: function(row, col)
    {
        let script = this._view[row];
        return (script.disabled ? "disabled" : "");
    },
    
    getCellText: function(row, col)
    {
        let script = this._view[row];
        
        switch (col.id)
        {
            case "tcol_name": return script.name;
            case "tcol_thumbnailType": return this._thumbnailTypeNames[script.thumbnailType];
            case "tcol_type": return this._typeNames[script.type];
            case "tcol_created":  return (script.created ? script.created.toLocaleFormat("%Y-%m-%d %H:%M") : "");
            case "tcol_modified": return (script.modified ? script.modified.toLocaleFormat("%Y-%m-%d %H:%M") : "");
            case "tcol_lastUsed": return (script.lastUsed ? script.lastUsed.toLocaleFormat("%Y-%m-%d %H:%M") : "");
            case "tcol_counter":  return script.counter;
            default: return "";
        }
    },
    
    getCellValue: function(row, col)
    {
        return (! this._view[row].disabled);
    },
    
    isEditable: function(row, col)
    {
        return (col.id == "tcol_enabled");
    },
    
    isSorted: function()
    {
        return (!! this._sortColumn);
    },
    
    setCellValue: function(row, col, value)
    {
        ScriptStore.setScriptDisabled(this._view[row].id, (value == "false"));
    },
    
    setTree: function(treeBoxObject)
    {
        this.treeBoxObject = treeBoxObject;
        
        if (! treeBoxObject)
            return;
        
        // init sortColumn
        this._sortColumn = null;
        for (let col = treeBoxObject.columns.getFirstColumn(); col; col = col.getNext())
        {
            let sortDirection = col.element.getAttribute("sortDirection");
            if ((sortDirection == "ascending") || (sortDirection == "descending"))
            {
                this._sortColumn = col;
                break;
            }
        }
    },
    
    isContainer: function(row) { return false; },
    isSeparator: function(row) { return false; },
    getLevel: function(row) { return 0; },
    getParentIndex: function(row) { return -1; },
    getImageSrc: function(row, col) { return null; },
    getRowProperties: function(row) { return ""; },
    getColumnProperties: function(colId, col) { return ""; },
}
